$(function () {
    var query = {},
        $view = $('.view'),
        $delete = $('.btn-delete'),
        $update = $('.btn-update'),
        $create = $('.btn-create'),
        $updatePermission = $('.btn-update-permission'),
        $log = $('.btn-log');
    var bars = getToolBtns();
    var config = {
        query: '/role/queryList?',//分页查询URL,
        create: '/role/create',//create,
        update: '/role/update',
        getPermission: '/role/getPermission/',
        'delete': '/role/delete'
    };


    $.when(getMenusList(), getMenusItemList(), getLoginUser())
        .done(function (list, menusItems, user) {
            menusItems = menusItems.list;
            var menusGroup = _.groupBy(list, 'level');
            var menusGroupByParentId = _.groupBy(list, 'pId');
            var menuLeaf = _.groupBy(_.filter(user.permissions, function (item) { //过滤掉数据权限
                return item.type;
            }), 'id');
            onClick(bars[0], function () {
                dialogForm(
                    {
                        fullScreen:true,
                        data: [
                            {
                                type: 'text',
                                label: '菜单名称',
                                require: true, // 是否必填
                                placeholder: '请输入菜单名称',
                                name: 'name'
                            },
                            {
                                type: 'text',
                                label: '排序号',
                                val: '0',
                                placeholder: '请输入排序号',
                                name: 'orderNum'
                            },
                        ],
                        submit: function (form) {
                            form.level = 1;
                            form.type1 = 'menu'; // 数据类型菜单
                            $.post('/category/add', form, function (res) {
                                if (res.code == 200) {
                                    fnSuccess("操作成功");
                                    window.location.href = window.location.href;
                                } else {
                                    fnFail("操作失败");
                                }
                            })
                        }
                    });
            });
            onClick(bars[1], function () {
                if (menusGroup[1] && menusGroup[1].length) {

                    dialogForm(
                        {
                            fullScreen:true,
                            data: [
                                {
                                    type: 'select',
                                    label: '上级菜单',
                                    require: true, // 是否必填
                                    placeholder: '请选择上级菜单名称',
                                    name: 'pId',
                                    options: menusGroup[1]
                                },
                                {
                                    type: 'text',
                                    label: '菜单名称',
                                    require: true, // 是否必填
                                    placeholder: '请输入菜单名称',
                                    name: 'name'
                                },
                                {
                                    type: 'text',
                                    label: '排序号',
                                    val: '0',
                                    placeholder: '请输入排序号',
                                    name: 'orderNum'
                                },
                            ],
                            shown: function () {
                                initSelect({
                                    data: menusGroup[1],
                                    name: 'pId',
                                    label: '上级菜单',
                                    change: function () {
                                        console.log(arguments);
                                    }
                                })
                            },
                            submit: function (form) {
                                form.level = 2;
                                form.type1 = 'menu';
                                $.post('/category/add', form, function (res) {
                                    if (res.code == 200) {
                                        fnSuccess("操作成功")
                                        window.location.href = window.location.href;
                                    } else {
                                        fnFail("操作失败");
                                    }
                                })
                            }
                        });
                } else {
                    fnFail("请首先创建一级菜单");
                }
            });
            var menusItemsGroup = _.groupBy(menusItems, 'categoryId');
            var group = _.filter(user.permissions, 'type');
            group = _.groupBy(group, 'id')
            var oneLevel = menusGroup['1'], treeNode = [];
            _.sortBy(oneLevel, 'orderNum').map(function (item, index) {
                if (menusGroupByParentId[item.id] && menusGroupByParentId[item.id].length) { // 包含二级菜单
                    menusGroupByParentId[item.id].map(function (item1, index) {
                        item1.pId = item.id;
                        item1.isParent = true;
                        item1.open = true;
                        item.id = item.id;

                        treeNode.push(item1);
                        menusItemsGroup[item1.id] = menusItemsGroup[item1.id] || [];
                        menusItemsGroup[item1.id].map(function (item2) {
                            if(group[item2.itemId]&&group[item2.itemId].length){
                                item2.pId = item1.id;
                                item2.id = item2.id + 500;
                                item2.name = group[item2.itemId][0].permissionName;
                                treeNode.push(item2);
                            }

                        })
                    });
                } else { // 叶子节点
                    menusItemsGroup[item.id] = menusItemsGroup[item.id] || [];
                    menusItemsGroup[item.id].map(function (item1) {
                        item1.pId = item.id;
                        item1.id = item1.id + 500;
                        treeNode.push(item1);
                    })
                }
                item.open = true;
                item.isParent = true;
                item.pId = 0;
                item.id = item.id
                treeNode.push(item);
            });
            zTree({
                eleId: 'ztree',
                data: treeNode,
                click: function (e, eleId, nodeItem, orderNum) {
                    if (menusGroupByParentId[nodeItem.id] && menusGroupByParentId[nodeItem.id].length)return;// 包含二级菜单
                    if (!nodeItem.isParent)return;// 叶子节点
                    dialogForm(
                        {
                            fullScreen:true,
                            data: [
                                {
                                    type: 'text',
                                    label: '菜单名称',
                                    require: true, // 是否必填
                                    val: nodeItem.name,
                                    disabled: true,
                                    placeholder: '请输入菜单名称',
                                    name: 'name'
                                },
                                {
                                    type: 'checkbox',
                                    label: '直接子菜单',
                                    //require: true, // 是否必填
                                    val: _.filter(user.permissions, function (item) { //过滤掉数据权限
                                        return item.type;
                                    }).map(function (item) {
                                        item.name = item.permissionName;
                                        return item;
                                    }),
                                    disabled: true,
                                    //placeholder: '请输入菜单名称',
                                    name: 'itemId'
                                },
                            ],
                            shown: function () {
                                menusItemsGroup[nodeItem.id].map(function (item1) {
                                    $('[name=itemId][value=' + item1.itemId + ']').length && setChecked($('[name=itemId][value=' + item1.itemId + ']'));
                                })
                            },
                            submit: function (form) {
                                form.categoryId = nodeItem.id;
                                if (menusItemsGroup[nodeItem.id] && menusItemsGroup[nodeItem.id].length) {
                                    form.ids = menusItemsGroup[nodeItem.id].map(function (item1) {
                                        return parseInt(item1.id) - 500;
                                    }).join(',');
                                }
                                form.type1 = 'menu';//
                                $.post('/categoryRelation/batchUpdate', form, function (res) {
                                    if (res.code == 200) {
                                        fnSuccess("操作成功");
                                        refreshPage();
                                    } else {
                                        fnFail("操作失败");
                                    }
                                })
                            }
                        });
                }
            }, user.permissions)
        });


    function view(items) {
        var $data = $(this).data('json');
        $.when(getDataByUrl(config.getPermission + $data.id, '$permission' + $data.id))
            .then(function (list) {
                var menusGroup = _.filter(list, function (item) {
                    return item.type == 1;
                });
                var accessGroup = _.filter(list, function (item) {
                    return item.type == 0;
                });
                $('.view-c').html(renderMenus(menusGroup) + renderAccess(accessGroup));
            })
            .fail(function (e) {
                console.log(e);
            });
    }
});

